home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2879 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: Rezonet.net!news
  2. From: ray@ultimate-tech.com (Ray Dunn)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Why isn't return address in the stack protected?
  5. Date: 24 Jan 1996 17:32:46 GMT
  6. Organization: Ultimate Technographics Inc.
  7. Message-ID: <4e5qfv$1587@ns.RezoNet.NET>
  8. References: <DLo4xF.MH@un.seqeb.gov.au> <1996Jan24.032914.8805@ohstpy>
  9. NNTP-Posting-Host: 204.19.230.7
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=US-ASCII
  12. X-Newsreader: WinVN 0.99.7
  13.  
  14. In article <DLo4xF.MH@un.seqeb.gov.au>, al012@svtstu.seqeb.gov.au 
  15. (Anthony Lee) writes:
  16. > void log_event(void)
  17. > {
  18. >       char message[256]; 
  19. >       int i;
  20. >       sprintf(message,
  21. >               "     Event, node: %d, seq:%08.8x, type:%02.2d, 
  22. > length:%03.3d, data: ",
  23. >               nodeid, me.seqno, me.type, me.length);
  24. >       for ( i = 0; i < me.length; i++)
  25. >              sprintf(&message[strlen(message)],"%02.2x 
  26. > ",me.data.array[i] & 0xff);
  27. >       printf("%s\n", message);
  28. > }
  29. > In the above code if the me.length is such that the resultant
  30. > string is longer than the size of message (> 256 bytes).  Then
  31. > my C program would happily sprintf into message.  The problem is
  32. > that it starts writing all over the stack causing the program
  33. > to fall over.  My question is why can't the run time environment
  34. > protect the stack from such access and flag an error?
  35.  
  36. Automatic variables are usually allocated from the same area of memory 
  37. as the stack (it's difficult to not use system-specific terms here).
  38. There is no way that a normal 'C' environment can differentiate your 
  39. writes to message and writes to outside those 256 bytes.  In order to 
  40. do so, the compiler would have to plant complex bounds checking code, 
  41. and in this case too, the "sprintf" and all the library routines would 
  42. also need to know the size of their arguments and check that you 
  43. remained within bounds.  Slow cumbersome run-time!
  44.  
  45. If message was not an automatic, but a global or static, then on some 
  46. systems it would occupy its own "data segment" (there I said it was 
  47. difficult to avoid system specific terms!), and the hardware would 
  48. cause an exception if an attempt was made to write outside its legal 
  49. bounds.
  50.  
  51. -- 
  52. Ray Dunn (opinions are my own) | Phone: (514) 938 9050
  53. Montreal                       | Phax : (514) 938 5225
  54. ray@ultimate-tech.com          | Home : (514) 630 3749
  55.  
  56.